package cn.azy.document.tool;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;

/**
 * @ Author     ：AZY.
 * @ Date       ：Created in 16:09 2019/10/24
 * @ Description：${DESCRIPTION}
 */
@Slf4j
public class PutDataToFile implements Runnable {
    private List<Map<String,String>> list;
    private String key;

    public PutDataToFile(List<Map<String,String>>  list, String key) {
        super();
        this.list = list;
        this.key = key;
    }



    @Override
    public void run() {
        OutputStream out = null;
        try {
            int columnNumCount = list.size();
            String excelName = "F:\\昌平雨量1\\"+key+".xlsx";
            // 读取Excel文档
            File finalXlsxFile = new File(excelName);
            //读取模板
            File file = new File("F:\\昌平雨量1\\1.xlsx");
            if(!finalXlsxFile.isFile()){
                //复制模板文件
                Files.copy(file.toPath(),finalXlsxFile.toPath());
            }
            FileInputStream in = new FileInputStream(finalXlsxFile);
            Workbook workBook = new XSSFWorkbook(in);

            // sheet 对应一个工作页
            Sheet sheet = workBook.getSheetAt(0);
            /**
             * 往Excel中写新数据
             */

            for (int j = 0; j < list.size(); j++) {
                // 创建一行：从第二行开始，跳过属性列
                Row row = sheet.createRow(j + 1);
                // 得到要插入的每一条记录
                Map<String,String> map = list.get(j);
                for (int k = 0; k <= columnNumCount; k++) {
                    // 在一行内循环
                    Cell first = row.createCell(0);
                    first.setCellValue(map.get("name"));

                    Cell second = row.createCell(1);
                    second.setCellValue(map.get("st"));

                    Cell third = row.createCell(2);
                    third.setCellValue(map.get("et"));

                    Cell fourth = row.createCell(3);
                    fourth.setCellValue(map.get("drp"));
                }
            }
            // 创建文件输出流，准备输出电子表格：这个必须有，否则你在sheet上做的任何操作都不会有效
            out =  new FileOutputStream(excelName);
            log.info("开始写入"+excelName);
            workBook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            try {
                if(out != null){
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
